import { isEmpty } from 'validator';
import * as moment from 'moment';
/**
 * 线程挂起
 * @param  {number} ms 挂起时长（毫秒）
 */
export const sleep = async (ms: number) => {
    await new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
};
/**
 * 线程挂起，与 saga 同时使用
 * @param  {number} ms 挂起时长（毫秒）
 */
export const sleepWithSaga = (ms: number) => {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
};

export const getQueryString = (name: string) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    const location = window.location.href;
    const r = location.substr(location.indexOf('?') + 1).match(reg);
    if (r !== null) {
        return decodeURIComponent(r[2]);
    }

    return null;
};

export const isEmptyString = (str: string | null | undefined) => {
    return (
        null === str ||
        undefined === str ||
        isEmpty(str)
    );
};

export const now = moment().format('YYYY-MM-DD HH:mm:ss');

const FULL_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
export const randomCode = () => {
    let code = (new Date()).getTime().toString();
    for (let i = 0; i < 6; i++) {
        const index = Math.floor(Math.random() * 36);
        code += FULL_CHARS[index];
    }

    return code;
};
export const getCutData = (data: any) => {
    const dString = JSON.stringify(data);
    const dBuffer = Buffer.from(dString);
    const buffers = [];
    const hexs = [];
    // 切割文件
    const dBufferLength = dBuffer.length;
    const chunkSize = 1024 * 1204;
    let startIndex = 0;
    let endIndex = 0;

    while (endIndex < dBufferLength) {
        endIndex = startIndex + chunkSize;
        if (endIndex > dBufferLength) {
            endIndex = dBufferLength;
        }
        buffers.push(
            dBuffer.slice(startIndex, endIndex)
        );
        hexs.push(
            buffers[buffers.length - 1].toString('hex')
        );
        startIndex = endIndex;
    }

    return hexs;
};

export const setDocumentTitle = (title: string) => {
    const versionTitle = `${title}-试用版`;

    return versionTitle;
};

export const initAnchorName = (id: string) => {
    return `page_${id}`;
};
